﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Project.DTO;
using Project.IService;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project.WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize(Roles ="Employer")]
    [Authorize]
    public class OrderController : ControllerBase
    {
        private readonly IOrderService orderService;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;

        public OrderController(
            IOrderService orderService,
            IMapper mapper,
            IConfiguration configuration
            )
        {
            this.orderService = orderService;
            this.mapper = mapper;
            this.configuration = configuration;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="obj">订单对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post(OrderPost obj)
        {
            var userId = HttpContext.User.Claims.FirstOrDefault(n => n.Type == "Id").Value;
            var order = mapper.Map<Order>(obj);
            order.UserId = Guid.Parse(userId);  // 用户id

            var time = DateTime.Now;

            // 订单明细
            order.Details = new List<OrderDetail>();  
            foreach(var tooth in obj.Tooths)
            {
                var detail = mapper.Map<OrderDetail>(tooth); // 订单明细

                // 附件
                List<OrderFiles> files = new List<OrderFiles>();
                foreach (var file in tooth.FileNames)
                {
                    files.Add(new OrderFiles() { Path = file, OrderDetail=detail, CreateAt= time});
                }

                var positions = mapper.Map<List<ToothPosition>>(tooth.ToothList); // 牙位列表
                positions.ForEach(p => { p.OrderDetail = detail; p.CreateAt = time; }); // 设置牙位对应的订单明细

                detail.Toothes.AddRange(positions);
                detail.Files = files;
                order.Details.Add(detail);
            }

           
            await orderService.AddAsync(order);

            return Ok(new { id = order.Id });
        }



        /// <summary>
        /// 根据订单id删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(Guid id)
        {
            await orderService.DeleteAsync(id);
            return Ok("删除完成！");
        }

        /// <summary>
        /// 根据订单编号查看订单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(Guid id)
        {
            var order = await orderService.GetOrderAsync(id);
            if (order == null)
                return NotFound("订单Id不存在");
            return Ok(order);
            
        }

        /// <summary>
        /// 按状态分页查询获取当前雇主的订单
        /// </summary>
        /// <param name="state">订单状态（0：发布（默认），1：草稿，2：已接单，3：已完成（待付款），4：已付款，5：已评价）</param>
        /// <param name="pageIndex">页码，默认值为1</param>
        /// <param name="pageSize">每页数量，默认值为8</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(int state=0,int pageIndex=1,int pageSize=8)
        {
            var userId = HttpContext.User.Claims.FirstOrDefault(n => n.Type == "Id").Value;
            int total;
            var list = await orderService.GetList<DateTime?>(o => o.State == state, pageSize, pageIndex, out total, r => r.CreateAt, false)
                .Select(o=>new { o.Id,o.OrderNo,o.CreateAt,o.State,o.ComplationTime,o.Employee.Name,o.ServiceType,
                    Details= o.Details.Select(d=>new {   // 订单明细
                        d.DesignTool,d.OuterNo,
                        Tooths=d.Toothes.Select(t=>new {    // 牙位信息
                            t.BottomLeft,t.BottomRight,t.TopLeft,t.TopRight,t.SumPrice,t.Product.Title}) })
                }).ToListAsync();

            return Ok(new { total = total, List = list });
        }
    

        /// <summary>
        /// 雇主修改订单信息，如果订单已接单，则不允许修改
        /// </summary>
        /// <param name="id">订单id</param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("id")]
        public async Task<IActionResult> Put(Guid id,OrderPost model)
        {
            var order = await orderService.GetList(n => n.Id == id).Select(o => new { o.Id, o.State }).FirstOrDefaultAsync();

            if (order==null)
                return NotFound("订单Id不存在！");
            if (order.State < 2)
                return BadRequest("订单已被其它用户接单，不允许修改！");

            var entity = mapper.Map<Order>(order);
            entity.Id = id;

            await orderService.EditAsync(entity);

            return Ok("修改完成！");
        }
    }
}
